eva.popup = {

	options : {
		loadingHtml : '<span class="popup_load_handler" style="display:block; text-align:center;"><img src="' + eva.d('/skins/meibooks/loading.gif') + '" /></span>',
		fixedPosition : false,
		resizePosition : false,
		allowDrag : false,
		closeHandler : true,
		overlayer : false,
		showLoading : true
	},

	setPositon: function(selector, connectedItem) {
		var height = $(selector).height();
		var width = $(selector).width();
		var top = parseInt($(window).height()) / 2 - height / 2;
		var left = parseInt( $(window).width()) / 2 - width / 2;

		$(selector).css({
			'position' : 'absolute',
			'top' : top,
			'left' : left
		});	
	},

	show : function(selector) {

		this.init(selector);
		this.setPositon(selector);
		$(selector).show();

	},

	showLoading : function(selector) {
		var popup = $(selector);

		$(" .popup_wrap", popup).hide();
		$(" .popup_load_handler", popup).show();
		
	},
	
	hideLoading : function(selector){
		var popup = $(selector);

		$(" .popup_wrap", popup).show();
		$(" .popup_load_handler", popup).hide();				  
	},

	//item is popup
	hide : function(selector) {
		$(selector).hide();
	},

	init : function(selector){
		var popup = $(selector);
		if(popup.data('eva_popup') === true) {
			return;
		}

		popup.wrapInner('<div class="popup_wrap" />');

		if(!$(" .popup_close_handler", popup)[0]) {
			popup.append('<span class="popup_close_handler"></span>');
			$(" .popup_close_handler", selector).click(function(){
				eva.popup.hide(selector);
			});

			$(selector).drag(function(event, target){
				$(this).css({
					top: target.offsetY,
					left: target.offsetX
				});	
			});
		}
		
		if(!$(" .popup_load_handler", selector)[0]) {
			$(selector).append(this.options.loadingHtml);
			this.hideLoading(selector);
		}

		$(selector).data('eva_popup', true);

	}

}

eva.slide = {

	optionsDefault : {
		triggers : '.slide_triggers li',
		contents : '.slide_content section',
		switchTriggers : function(triggers){
			$(triggers).removeClass('current');
		},
		switchContents : function(contents){
			$(contents).removeClass('current');
		},
		switchTrigger : function(trigger){
			$(trigger).addClass('current');
		},
		switchContent : function(content){
			$(content).addClass('current');
		}
	},

	init : function(options){

		var i;
		var optionsDefault = this.optionsDefault;
		for(i in options) {
			optionsDefault[i] = options[i];
		}
		options = optionsDefault;

		$(options.triggers).click(function(){
			var index = $(this).index();
			var triggers = $(options.triggers);
			var contents = $(options.contents);

			//click self
			if($(this).hasClass('current')) {
				return false;
			}

			options.switchTriggers(triggers);
			options.switchContents(contents);

			options.switchTrigger($(triggers).eq(index));
			options.switchContent($(contents).eq(index));
			return false;
		});	   
	}

}




eva.tip = {

	tiptip_holder : '',

	tiptip_content : '',

	tiptip_arrow : '',

	timeout : false,

	message : '',

	inited : false,

	opts : { 
		activation: "hover",
		keepAlive: false,
		maxWidth: "200px",
		edgeOffset: 3,
		defaultPosition: "top",
		delay: 50,
		fadeIn: 200,
		fadeOut: 200,
		attribute: "title",
		content: false, // HTML or String to fill TipTIp with
		enter: function(){},
		exit: function(){}
	},

	init : function(){
		if(this.inited === true)
			return;

	 	if($("#tiptip_holder").length <= 0){
	 		this.tiptip_holder = $('<div id="tiptip_holder" style="max-width:'+ this.opts.maxWidth +';"></div>');
			this.tiptip_content = $('<div id="tiptip_content"></div>');
			this.tiptip_arrow = $('<div id="tiptip_arrow"></div>');
			$("body").append(this.tiptip_holder.html(this.tiptip_content).prepend(this.tiptip_arrow.html('<div id="tiptip_arrow_inner"></div>')));
		} else {
			this.tiptip_holder = $("#tiptip_holder");
			this.tiptip_content = $("#tiptip_content");
			this.tiptip_arrow = $("#tiptip_arrow");
		}

		this.inited = true;
	},

	show : function(org_elem,message){
		if(message) {
			this.tiptip_content.html(message);
		}
		this.tiptip_holder.hide().removeAttr("class").css("margin","0");
		this.tiptip_arrow.removeAttr("style");

		var top = parseInt(org_elem.offset()['top']);
		var left = parseInt(org_elem.offset()['left']);
		var org_width = parseInt(org_elem.outerWidth());
		var org_height = parseInt(org_elem.outerHeight());
		var tip_w = this.tiptip_holder.outerWidth();
		var tip_h = this.tiptip_holder.outerHeight();
		var w_compare = Math.round((org_width - tip_w) / 2);
		var h_compare = Math.round((org_height - tip_h) / 2);
		var marg_left = Math.round(left + w_compare);
		var marg_top = Math.round(top + org_height + this.opts.edgeOffset);
		var t_class = "";
		var arrow_top = "";
		var arrow_left = Math.round(tip_w - 12) / 2;

		if(this.opts.defaultPosition == "bottom"){
			t_class = "_bottom";
		} else if(this.opts.defaultPosition == "top"){ 
			t_class = "_top";
		} else if(this.opts.defaultPosition == "left"){
			t_class = "_left";
		} else if(this.opts.defaultPosition == "right"){
			t_class = "_right";
		}

		var right_compare = (w_compare + left) < parseInt($(window).scrollLeft());
		var left_compare = (tip_w + left) > parseInt($(window).width());

		if((right_compare && w_compare < 0) || (t_class == "_right" && !left_compare) || (t_class == "_left" && left < (tip_w + this.opts.edgeOffset + 5))){
			t_class = "_right";
			arrow_top = Math.round(tip_h - 13) / 2;
			arrow_left = -12;
			marg_left = Math.round(left + org_width + this.opts.edgeOffset);
			marg_top = Math.round(top + h_compare);
		} else if((left_compare && w_compare < 0) || (t_class == "_left" && !right_compare)){
			t_class = "_left";
			arrow_top = Math.round(tip_h - 13) / 2;
			arrow_left =  Math.round(tip_w);
			marg_left = Math.round(left - (tip_w + this.opts.edgeOffset + 5));
			marg_top = Math.round(top + h_compare);
		}

		var top_compare = (top + org_height + this.opts.edgeOffset + tip_h + 8) > parseInt($(window).height() + $(window).scrollTop());
		var bottom_compare = ((top + org_height) - (this.opts.edgeOffset + tip_h + 8)) < 0;

		if(top_compare || (t_class == "_bottom" && top_compare) || (t_class == "_top" && !bottom_compare)){
			if(t_class == "_top" || t_class == "_bottom"){
				t_class = "_top";
			} else {
				t_class = t_class+"_top";
			}
			arrow_top = tip_h;
			marg_top = Math.round(top - (tip_h + 5 + this.opts.edgeOffset));
		} else if(bottom_compare | (t_class == "_top" && bottom_compare) || (t_class == "_bottom" && !top_compare)){
			if(t_class == "_top" || t_class == "_bottom"){
				t_class = "_bottom";
			} else {
				t_class = t_class+"_bottom";
			}
			arrow_top = -12;						
			marg_top = Math.round(top + org_height + this.opts.edgeOffset);
		}

		if(t_class == "_right_top" || t_class == "_left_top"){
			marg_top = marg_top + 5;
		} else if(t_class == "_right_bottom" || t_class == "_left_bottom"){		
			marg_top = marg_top - 5;
		}
		if(t_class == "_left_top" || t_class == "_left_bottom"){	
			marg_left = marg_left + 5;
		}
		this.tiptip_arrow.css({"margin-left": arrow_left+"px", "margin-top": arrow_top+"px"});
		this.tiptip_holder.css({"margin-left": marg_left+"px", "margin-top": marg_top+"px"}).attr("class","tip"+t_class);

		if (this.timeout){ clearTimeout(this.timeout); }
		this.timeout = setTimeout(function(){ 
				eva.tip.tiptip_holder.stop(true,true).fadeIn(eva.tip.opts.fadeIn);
		}, this.opts.delay);	
	},

	hide : function(){
		if (this.timeout)
			clearTimeout(this.timeout);

		this.tiptip_holder.fadeOut(this.opts.fadeOut);
	}

}

eva.form = {
	currElem : {},

	currErr : {},

	onfocusin : function(){
		eva.tip.show($(this),eva.form.currErr.html());
	},

	onfocusout : function(){
		eva.tip.hide(); 
	},

	options : {
		errorClass : 'error',
		onfocusin: function(element) {
			if(!$(element).hasClass("error"))
				return;

			this.element(element);
		},
        onfocusout: function(element) {
			if ( !this.checkable(element) && (element.name in this.submitted || !this.optional(element)) ) {
				this.element(element);
			}
			//alert(element);
        },
		errorPlacement: function(error, element) {
			eva.form.currElem = element;
			eva.form.currErr = error;
			if(!$(element).hasClass("error"))
				return;

			//eva.p(element[0].id);
			eva.tip.show($(element),eva.form.currErr.html());
			$(element).bind("focus", eva.form.onfocusin).bind("blur", eva.form.onfocusout);
		},
		success: function(label) {
			$(eva.form.currElem).unbind("focus", eva.form.onfocusin).unbind("blur", eva.form.onfocusout);
			eva.tip.hide();	
		}
	},

	messages : {
		"en" : 
			{
				required: "This field is required.",
				remote: "Please fix this field.",
				email: "Please enter a valid email address.",
				url: "Please enter a valid URL.",
				date: "Please enter a valid date.",
				dateISO: "Please enter a valid date (ISO).",
				number: "Please enter a valid number.",
				digits: "Please enter only digits.",
				creditcard: "Please enter a valid credit card number.",
				equalTo: "Please enter the same value again.",
				accept: "Please enter a value with a valid extension.",
				maxlength: $.validator.format("Please enter no more than {0} characters."),
				minlength: $.validator.format("Please enter at least {0} characters."),
				rangelength: $.validator.format("Please enter a value between {0} and {1} characters long."),
				range: $.validator.format("Please enter a value between {0} and {1}."),
				max: $.validator.format("Please enter a value less than or equal to {0}."),
				min: $.validator.format("Please enter a value greater than or equal to {0}.")
			},
		"zh" : 
			{
				required: "这是一个必填项",
				remote: "输入不匹配",
				email: "这不是一个正确的电子邮件地址格式",
				url: "这不是一个有效的网址",
				date: "这不是一个有效的日期",
				dateISO: "这不是一个有效的日期(ISO格式)",
				number: "请输入数字",
				digits: "请输入纯数字",
				creditcard: "这不是一个有效的信用卡号",
				equalTo: "两次输入不一致",
				accept: "请输入允许的扩展名",
				maxlength: $.validator.format("最多可以输入 {0} 个字符"),
				minlength: $.validator.format("至少要输入 {0} 个字符"),
				rangelength: $.validator.format("请输入 {0} 到 {1} 个字符"),
				range: $.validator.format("请输入一个在 {0} 到 {1} 之间的数字"),
				max: $.validator.format("请输入一个不大于 {0} 的数字"),
				min: $.validator.format("请输入一个至少为 {0} 的数字")
			}
	},

	rules : {
		remote: function(value, element, param) {
			if ( this.optional(element) )
				return "dependency-mismatch";

			var previous = this.previousValue(element);
			if (!this.settings.messages[element.name] )
				this.settings.messages[element.name] = {};
			previous.originalMessage = this.settings.messages[element.name].remote;
			this.settings.messages[element.name].remote = previous.message;

			param = typeof param == "string" && {url:param} || param;

			if ( this.pending[element.name] ) {
				return "pending";
			}
			if ( previous.old === value ) {
				return previous.valid;
			}

			previous.old = value;
			var validator = this;
			this.startRequest(element);
			var data = {};
			data[element.name] = value;
			$.ajax($.extend(true, {
				url: param,
				mode: "abort",
				port: "validate" + element.name,
				dataType: "json",
				data: data,
				success: function(response) {
					validator.settings.messages[element.name].remote = previous.originalMessage;
					//EVA FIX
					var valid = response.data === '';
					if ( valid ) {
						var submitted = validator.formSubmitted;
						validator.prepareElement(element);
						validator.formSubmitted = submitted;
						validator.successList.push(element);
						validator.showErrors();
					} else {
						var errors = {};
						//EVA FIX
						var message = validator.defaultMessage( element, "remote" );
						errors[element.name] = previous.message = $.isFunction(message) ? message(value) : message;
						validator.showErrors(errors);
					}
					previous.valid = valid;
					validator.stopRequest(element, valid);
				}
			}, param));
			return "pending";
		}
	},

	valid : {},
	
	init : function(){
		eva.tip.init();

		var lang = eva.config.lang;
		if(this.messages[lang]) {
			$.validator.messages = this.messages[lang];
		}

		if(Modernizr !== undefined)  {
		    if (!Modernizr.input.placeholder){
				$('input[placeholder]:not(:password)').each(function(){
					$(this).DefaultValue($(this).attr("placeholder"));		
				});
    		}
		}

		$.validator.methods.remote = eva.form.rules.remote;

		$("form:not(.novalid)").each(function(){
			$(this).validate(eva.form.options);
		});

		var router = eva.getRouterName();
		if(this.valid[router]) {
			this.valid[router]();
		}
	}

}
